<template>
  <view class="wrap public-font" :style="colorStyle">
    <view v-if="tabIndex==1" class="top-tip">
      自行预约快递后，请务必在此处填写快递单号
    </view>
    <view class="tab-box-public">
      <view @click="tabIndex=item.value" class="tab-item" v-for="(item,index) in tabList" :class="tabIndex === item.value ? 'tab-active' : ''" >
        {{item.name}}
      </view>
    </view>
    <view class="p-20">
      <view v-for="(item,index) in cartInfo" :key="index" class="order_goods bg--w111-fff">
        <view class="flex">
          <image v-if="item.productInfo.attrInfo" :src='item.productInfo.attrInfo.image' class="w-136 h-136 rd-16rpx"></image>
          <image v-else :src='item.productInfo.image' class="w-136 h-136 rd-16rpx"></image>
          <view class="flex-1 flex justify-between pl-20">
            <view class="flex-1">
              <view class="w-full line2 fs-28 lh-40rpx">
                {{item.productInfo.store_name}}
              </view>
              <view class="w-full line1 fs-24 text--w111-999 lh-34rpx mt-8">{{item.productInfo.attrInfo.suk_alias}}</view>
            </view>
<!--            <view class="flex-1 flex-col items-end">-->
<!--            </view>-->
          </view>
        </view>
      </view>
    </view>

    <view v-if="tabIndex==0" class="address-box">
      <view class="item item-1">
        <view class="line"></view>
        <view class="l">寄</view>
        <view class="r" v-if="addressInfo.address">
          <view class="r-1 mb-10">
            {{ addressInfo.real_name }}：{{ addressInfo.phone }}
          </view>
          <view class="r-2">
            {{ addressInfo.address }}
          </view>
        </view>
        <view class="r" v-else>
          请重新选择寄件地址
        </view>
        <view class="btn" @click="openAddress()">
          选择地址
        </view>
      </view>
      <view class="item">
        <view class="l l-2">收</view>
        <view class="r">
          <view class="r-1">
            {{platformAddress.real_name}}：{{platformAddress.phone}}
          </view>
          <view class="r-2">
            {{platformAddress.address}}
          </view>
        </view>
      </view>
    </view>

    <view v-if="tabIndex==0" class="time-box">
      <view class="item time-item">
        <view class="l">上门取件时间</view>
        <view class="r fw-bold" @click="timeShow=true">
          <view v-if="showTime">{{showTime}}</view>
          <view v-else>请选择时间</view>
          <text class='iconfont icon-ic_rightarrow'></text>
        </view>
      </view>
      <view class="item return-item">
        <view class="l">归还方式</view>
        <view class="r ">
          <text class="fw-bold">{{sfExpress.businessTypeDesc}}</text>
          <text class="fs-20 px-12">预估</text>
          <text class="fs-22 fw-bold">￥{{sfExpress.fee}}</text>
          <view class="tip text-red">运费以顺丰最终价格为准，平台为预收，多退少补</view>
        </view>
      </view>
    </view>

    <view v-if="tabIndex==0" class="tip-box">
      <view class="fs-26 mb-20">发货须知</view>
      <view class="mb-10">1、订单归还产生的物流运费由用户承担</view>
      <view class="mb-10">2、预约上门取件时支付运费后请勿让快递员修改付款方式，避免重复支付运费</view>
      <view class="mb-10">3、发货前请确保已为您的商品添加包装盒加固，因物流原因造成的商品损失{{ configData.site_name }}概不负责</view>
      <view class="mb-10">4、归还时间以物流中的快递揽收时间为准，请合理预约上门取件时间</view>
    </view>


    <view v-if="tabIndex==1" class="input-box">
      <view class="return-item">
        <view class="l l-2">收</view>
        <view class="r">
          <view class="r-1">
            {{platformAddress.real_name}}：{{platformAddress.phone}}
          </view>
          <view class="r-2">
            {{platformAddress.address}}
          </view>
        </view>
        <view class="btn text-blue" @click="copy">
          复制地址
        </view>
      </view>
      <view class="dan-item">
        <view>
          <text class="ebao-iconfont ebao-kuaididanhao"></text>
          <text class="px-12">快递单号</text>
          <text class="text--w111-999">
            (平台仅支持顺丰)
          </text>
        </view>
        <view class="input-wrap mt-20">
          <input v-model="delivery_id" placeholder="请输入快递单号" />
        </view>
      </view>
    </view>

    <view v-if="tabIndex==1" class="tip-box">
      <view class="fs-26 mb-20">发货须知</view>
      <view class="mb-10">1、自寄快递仅支持顺丰，请您自行支付运费</view>
      <view class="mb-10">2、请勿使用到付，到付件会导致仓库拒收</view>
      <view class="mb-10">3、发货前请确保已为您的商品添加包装盒加固，因物流原因造成的商品损失有奢租概不负责</view>
      <view class="mb-10">4、归还时间以物流中的快递揽收时间为准，请合理预约上门取件时间</view>
    </view>



    <view class="bottom-box">
      <view v-if="tabIndex==0" @click="save" class="btn-square w-full">预约归还</view>
      <view v-if="tabIndex==1" @click="save" class="btn-square w-full">快递已寄出，确认归还</view>
    </view>

    <base-drawer mode="bottom" :visible="timeShow" background-color="transparent" mask maskClosable @close="timeShow=false">
      <view class="time-pop">
        <view class="title">
          <view class="l">选择上门时间</view>
          <text @click="timeShow=false" class="ebao-iconfont ebao-guanbi fs-20"></text>
        </view>
        <view class="time-con">
          <scroll-view class="aside" scroll-y="true" scroll-with-animation='true'>
            <view
                v-for="(day, index) in timeList"
                :key="index"
                class="item"
                :class="{'item-active': timeDayIndex === index}"
                @click="timeDayIndex = index;timeTimeIndex=0"
            >
              {{ day.dateLabel }}
            </view>
          </scroll-view>
          <scroll-view class="content" scroll-y="true" scroll-with-animation='true'>
            <view
                v-for="(slot, idx) in timeList[timeDayIndex].slots"
                :key="idx"
                class="item"
                :class="{'item-active': timeTimeIndex === idx}"
                @click="timeTimeIndex = idx"
            >
              {{ slot.label }}
            </view>
          </scroll-view>
        </view>
      </view>
    </base-drawer>

    <addressWindow ref="addressWindow" :isDaike="true"  :address='address' @OnChangeAddress="OnChangeAddress" @changeClose="changeClose"></addressWindow>
  </view>
</template>

<script>
import colors from "@/mixins/color";
import {getOrderDetail} from "@/api/order";
import addressWindow from "@/components/addressWindow/index.vue";
import {
  buyoutPay,
  createSf,
  getPlatformAddress,
  getSfPrice,
  getZeroVipList,
  paySf,
  returnGoods
} from "@/api/leaseOrder";
export default {
  components: {addressWindow},
  mixins: [colors],
  data() {
    return {
      configData: this.$Cache.get('BASIC_CONFIG'),
      cartInfo: {},
      orderInfo: {},
      tabIndex:0,
      tabList:[
        {
          name:'上门取件',
          value:0
        },
        {
          name:'自寄快递',
          value:1
        }
      ],
      timeShow:false,
      timeList:[],
      timeDayIndex:0,
      timeTimeIndex:0,
      showTime:'', // 展示时间
      addressId:'',
      addressList: [],
      address: { address: false }, //地址组件

      // 提交参数
      order_id:'',
      startTime:'', // 实际时间
      addressInfo:{},
      platformAddress:{},
      sfExpress:{
        fee:'-'
      },

      back_id:'',
      // 自己快递单号
      delivery_id:'',
      sfExpressInfo:{}
    }
  },
  watch:{
    timeShow(){
      if(!this.timeShow){
        // 重新计算运费
        this.expressTime()
      }
    }
  },
  onLoad(options){
    this.order_id = options.order_id
    this.getOrderInfo()
  },
  methods:{
    // 设置取件时间
    expressTime(){
      // 展示时间
      let dayLabel=this.timeList[this.timeDayIndex].dateLabel
      let timeLabel=this.timeList[this.timeDayIndex].slots[this.timeTimeIndex].label
      this.showTime=dayLabel+' '+timeLabel

      // 收件时间
      let day=this.timeList[this.timeDayIndex].date
      let time=this.timeList[this.timeDayIndex].slots[this.timeTimeIndex].value
      this.startTime=day+' '+time.split('-')[0]+':00'

      this.getSfPrice()
    },
    // 顺丰预估价格
    getSfPrice(){
      getSfPrice({
        post_time:this.startTime,
        receiver:this.platformAddress,
        sender:this.addressInfo
      }).then(res=>{
        this.sfExpress=res.data
      })
    },
    getOrderInfo(){
      getOrderDetail(this.order_id).then(res=>{
        this.cartInfo = res.data.cartInfo;
        this.orderInfo=res.data
        // 平台地址
        this.getPlatformAddress()

        // 自寄快递-默认填充顺丰信息
        res.data.express_list.forEach(item=>{
          if(item.code==='shunfengkuaiyun'){
            this.sfExpressInfo=item
          }
        })
      })
    },
    generatePickupTime() {
      const result = [];
      const now = new Date();

      // 获取某一天的日期字符串，格式：YYYY-MM-DD
      function getDateString(date) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      }

      // 格式化时间为 hh:mm
      function formatTime(date) {
        return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      }

      // 添加时间段
      function addTimeSlots(dateLabel, baseDate) {
        const dateStr = getDateString(baseDate);
        const slots = [];

        // 设置开始和结束时间
        const startHour = 9;
        const endHour = 18;

        // 当前小时
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();

        // 如果是今天，并且还没到9点，则从当前时间开始
        let hourStart = baseDate.getTime() === now.getTime() ? Math.max(currentHour, startHour) : startHour;

        for (let hour = hourStart; hour < endHour; hour++) {
          const startTime = new Date(baseDate);
          startTime.setHours(hour, 0, 0, 0);

          const endTime = new Date(startTime);
          endTime.setHours(hour + 1);

          // 如果是今天，且是第一个小时段，则显示“一小时内”
          if (baseDate.getTime() === now.getTime() && hour === currentHour) {
            const nextHour = new Date(now.getTime() + 60 * 60 * 1000);
            slots.push({
              // label: `一小时内(${formatTime(now)}-${formatTime(nextHour)})`,
              label: `一小时内`,
              value: `${formatTime(now)}-${formatTime(nextHour)}`
            });
          } else {
            const startStr = `${String(hour).padStart(2, '0')}:00`;
            const endStr = `${String(hour + 1).padStart(2, '0')}:00`;
            slots.push({
              label: `${startStr}-${endStr}`,
              value: `${startStr}-${endStr}`
            });
          }
        }

        if (slots.length > 0) {
          result.push({ dateLabel, date: dateStr, slots });
        }
      }

      // 生成今天、明天、后天的时间段
      for (let i = 0; i < 3; i++) {
        const day = new Date(now);
        day.setDate(now.getDate() + i);
        const labels = ['今天', '明天', '后天'];
        addTimeSlots(labels[i], day);
      }

      console.log('result',result)
      this.timeList=result

      // 计算默认当前时间运费
      this.expressTime()
    },
    openAddress(){
      this.address.address = true;
      // 获取用户收货地址列表
      this.$nextTick(function() {
        this.$refs.addressWindow.getAddressList();
      })
    },
    // 选择地址
    OnChangeAddress: function(addressID,addressInfo) {
      this.addressInfo={
        real_name:addressInfo.real_name,
        phone:addressInfo.phone,
        address:addressInfo.detail,
        province:addressInfo.province,
        city:addressInfo.city,
        county:addressInfo.district
      }
      this.changeClose()
      // 重新计算运费
      this.expressTime()
    },
    changeClose: function() {
      this.$set(this.address, 'address', false);
    },
    copy() {
      let that = this
      uni.setClipboardData({
        data: this.platformAddress.real_name+' '+this.platformAddress.phone+' '+this.platformAddress.address,
        success: function () {
          that.$util.Tips({
            title: '复制成功'
          })
        }
      });
    },
    save(){
      // 预约快递
      if(this.tabIndex==0){
        if(!this.addressInfo.address){
          return this.$util.Tips({
            title: '请重新选择寄件地址'
          });
        }
        this.createSf('n').then(res=>{
          if(res.status===200){
            // 支付运费
            this.paySf()
          }
        })
      }else{
        let that = this
        if (!this.delivery_id){
          return this.$util.Tips({
            title: '请输入快递单号'
          });
        }
        if(this.delivery_id.toLowerCase().indexOf('sf') === -1){
          return this.$util.Tips({
            title: '请使用顺丰快递'
          });
        }
        returnGoods(this.orderInfo.id,{
          delivery_type:1,
          delivery_name:this.sfExpressInfo.name,
          delivery_id:this.delivery_id
        }).then(res => {
          if(res.status===200){
            this.$util.Tips({
              title: '提交成功'
            });
            uni.navigateBack({})
          }
        })
      }
    },
    // 平台地址
    getPlatformAddress(){
      getPlatformAddress({
        both:'y',
        order_id:this.orderInfo.id
      }).then(res=>{
        this.platformAddress=res.data.receiver
        this.addressInfo=res.data.sender
        // 生成取件时间
        this.generatePickupTime()
      })
    },
    createSf(pay_success,back_id){
      let form={
        back_id:back_id,
        order_id:this.orderInfo.id,
        receiver:this.platformAddress,
        sender:this.addressInfo,
        post_time:this.startTime,
        arrival_time:this.sfExpress.deliverTime.split(',')[1],
        fee:this.sfExpress.fee,
        logistics_name:this.sfExpress.businessTypeDesc,
        pay_success:pay_success
      }
      return createSf(form).then(res=>{
        this.back_id=res.data.back_id
        return res
      }).catch(err=>{
        if(err=='商品信息丢失'){
          let that=this
          uni.showModal({
            title: '提示',
            content: `预约失败，请选择自寄快递`,
            showCancel:false,
            confirmText:'我知道了',
            success: function (res) {
              if (res.confirm) {
                that.tabIndex=1
              }
            }
          })
        }
      })
    },

    // 支付运费
    paySf(){
      uni.showLoading({
        title: '加载中...'
      })
      let that=this
      paySf(that.orderInfo.id,{
        paytype:'alipay',
        from:'ali_routine',
        quitUrl:'pages/goods/lease_installment/index',
        record_id:that.back_id,
      }).then(res=>{
        if(res.status===200){
          if(res.data.status&&res.data.status==='ALIPAY_PAY'){
            let status = res.data.status,
                orderId = res.data.result.order_id || '',
                jsConfig = res.data.result.jsConfig;
            switch (status) {
              case 'ALIPAY_PAY':
                uni.requestPayment({
                  provider: 'alipay',
                  orderInfo: jsConfig.tradeNo,
                  success: (e) => {
                    // 支付成功
                    if(e.resultCode!="6001"){
                      let that=this
                      this.createSf('y',that.back_id).then(res=>{
                        uni.redirectTo({
                          url:`/pages/goods/lease_order_return/success?order_id=${this.order_id}&back_id=${res.data.back_id}&showTime=${this.showTime}`
                        })
                      }).catch(err=>{
                        uni.redirectTo({
                          url:`/pages/goods/lease_order_return/record?order_id=${this.order_id}`
                        })
                      })
                    }
                  }
                });
                break;
            }
          }
        }
      }).finally(() => {
        uni.hideLoading()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding-bottom: 300rpx;
}
.top-tip{
  background: #ff4d4d;
  color: #fff;
  text-align: center;
  padding: 10rpx;
  font-size: 22rpx;
}
.order_goods{
  padding: 20rpx;
}
.tab-box-public{
  justify-content: space-between;
  padding: 0 200rpx;
}

.address-box{
  background: #fff;
  padding: 30rpx;
  .item-1{
    position: relative;
    padding-bottom: 60rpx;
    .line{
      position: absolute;
      height: 100%;
      border: 1rpx dashed #333;
      left: 25rpx;
      top: 25rpx;
    }
  }
  .item{
    display: flex;
    .l{
      background: #029eff;
      width: 50rpx;
      height: 50rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      margin-right: 30rpx;
      z-index: 10;
    }
    .l-2{
      background: #333333;
    }
    .r{
      flex:1;
      padding-top: 8rpx;
    }
    .btn{
      align-self: center;
      margin-left: 20rpx;
      padding-left: 10rpx;
      color: #999;
      margin-top: 20rpx;
      border-left: 1rpx solid  #ddd;
      line-height: 1;
    }
  }
}

.time-box {
  background: #fff;
  padding: 0 30rpx;
  margin-top: 20rpx;
  .item{
    padding: 36rpx 20px;
    border-bottom: 1rpx solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    &:last-child{
      border-bottom: none;
    }
    .l{
      color: #333;
    }
    .r{

    }
  }
  .time-item{
    .r{
      display: flex;
      align-items: center;
    }
  }
  .return-item{
    .r{
      position: relative;
      .tip{
        position: absolute;
        font-size: 18rpx;
        white-space: nowrap;
        right: 0;
      }
    }
  }
}
.tip-box{
  background: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
}


.time-pop{
  background: #fff;
  .title{
    //font-size: 26rpx;
    padding: 30rpx;
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .l{
      font-weight: bold;
    }
  }
  .time-con{
    display: flex;
    height: 60vh;
  }
  .aside{
    width: 150rpx;
    height: 100%;
    background: #f5f5f5;
    .item{
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
    }
    .item-active{
      background: #fff;
      color: #fe5f5f;
    }
  }
  .content{
    flex:1;
    height: 100%;
    .item{
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
    }
    .item-active{
      background: #fff;
      color: #fe5f5f;
    }
  }
}

.bottom-box{
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  border-top: 1rpx solid #f5f5f5;
  background: #fff;
  .btn-square{
    height: 80rpx;
  }
}

.input-box{
  background: #fff;
  padding:30rpx;
  .return-item{
    display: flex;
    border-bottom: 1rpx solid #f5f5f5;
    padding-bottom: 20rpx;
    .l{
      background: #029eff;
      width: 50rpx;
      height: 50rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      margin-right: 30rpx;
      z-index: 10;
    }
    .l-2{
      background: #333333;
    }
    .r{
      flex:1;
      padding-top: 8rpx;
    }
    .btn{
      align-self: center;
      margin-left: 20rpx;
      padding-left: 20rpx;
      margin-top: 20rpx;
      line-height: 1;
      text-decoration: underline;
    }
  }

  .dan-item{
    padding-top: 20rpx;
    .input-wrap{
      width: 100%;
      height: 80rpx;
      background: #f5f5f5;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      input{
        font-size: 24rpx;
        background: #f5f5f5 !important;
      }
    }
  }
}
</style>